package com.denimgroup.threadfix.data.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.denimgroup.threadfix.data.dao.VulnerabilityCommentDao;
import com.denimgroup.threadfix.data.entities.VulnerabilityComment;

@Repository
public class HibernateVulnerabilityCommentDao implements VulnerabilityCommentDao {

	private SessionFactory sessionFactory;

	@Autowired
	public HibernateVulnerabilityCommentDao(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<VulnerabilityComment> retrieveAllForVuln(Integer vulnId) {
		return sessionFactory.getCurrentSession()
				.createCriteria(VulnerabilityComment.class)
				.add(Restrictions.eq("vulnerability.id", vulnId))
				.add(Restrictions.eq("active", true))
				.addOrder(Order.asc("id"))
				.list();
	}

	@Override
	public void saveOrUpdate(VulnerabilityComment comment) {
		sessionFactory.getCurrentSession().save(comment);
	}

	@Override
	public void delete(VulnerabilityComment comment) {
		comment.setActive(false);
		comment.setModifiedDate(new Date());
		if (comment.getVulnerability() != null) {
			comment.setDeletedVulnerabilityId(comment.getVulnerability().getId());
		}
		comment.setVulnerability(null);
		saveOrUpdate(comment);
	}

}
